package ru.ifmo.ct.network.brafs;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

/**
 * @author Alex Vikharev vikharev@yandex-team.ru
 *         created 20.04.12
 */
public class Utils {

    public static final int DEFAULT_BUFFER_SIZE = 1024;

    public static ByteBuffer read(final InputStream inputStream, final int bufferSize) throws IOException {
        final ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
        final byte[] readBuffer = new byte[bufferSize];
        int readCount = 0;
        while (readCount != -1 && buffer.position() < bufferSize) {
            readCount = inputStream.read(readBuffer);
            if (readCount != -1) {
                buffer.put(readBuffer, 0, readCount);
            }
        }
        return buffer;
    }

    public static ByteBuffer readSegment(final InputStream input) throws IOException {
        final int size = readInt(input);
        return read(input, size);
    }

    public static ByteBuffer readCommand(final InputStream inputStream, final int bufferSize) throws IOException {
        final ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
        final ByteBuffer commandBody = read(inputStream, 21);
        if (commandBody.position() < 21) {
            return ByteBuffer.allocate(0);
        }
        buffer.put(commandBody.array());
        final ByteBuffer otherPart = read(inputStream, commandBody.getInt(17));
        buffer.put(otherPart.array());
        return buffer;
    }

    public static ByteBuffer readCommand(final InputStream inputStream) throws IOException {
        return readCommand(inputStream, DEFAULT_BUFFER_SIZE);
    }

    public static int readInt(final InputStream inputStream) throws IOException {
        final ByteBuffer buffer = read(inputStream, 4);
        return buffer.getInt(0);
    }

    public static ByteBuffer read(final InputStream inputStream) throws IOException {
        return read(inputStream, DEFAULT_BUFFER_SIZE);
    }


}
